package com.zoe.onelink.core.encryptor.algorithm;

import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import cn.hutool.crypto.asymmetric.KeyType;
import cn.hutool.crypto.asymmetric.RSA;
import com.zoe.onelink.common.enumeration.ExceptionCodeEnum;
import com.zoe.onelink.common.exception.ApiException;
import com.zoe.onelink.core.property.EncryptKeyPair;
import com.zoe.onelink.core.property.OnelinkProperties;

/**
 * <p>标题: </p>
 * <p>描述: </p>
 * <p>版权: Copyright (c) 2021</p>
 * <p>公司: 智业软件股份有限公司</p>
 *
 * @version: 1.0
 * @author: ruansheng
 * @date: 2021-11-15
 */
public class RsaEncryptFieldAlgorithm extends AbstractEncryptFieldAlgorithm {

    private final RSA rsa;

    public RsaEncryptFieldAlgorithm(OnelinkProperties onelinkProperties, EncryptKeyPair keyPair) {

        super(onelinkProperties.getWeb().getEncrypt());

        if (keyPair == null || StrUtil.isBlank(keyPair.getPrivateKey())) {
            this.ex = ApiException.createEx(ExceptionCodeEnum.SERIALIZATION_ENCRYPT_KEY_PAIR_NOT_NULL, "RSA", "PRIVATE KEY");
            this.rsa = null;
        } else if (StrUtil.isBlank(keyPair.getPublicKey())) {
            this.ex = ApiException.createEx(ExceptionCodeEnum.SERIALIZATION_ENCRYPT_KEY_PAIR_NOT_NULL, "RSA", "PUBLIC KEY");
            this.rsa = null;
        } else {
            this.rsa = SecureUtil.rsa(keyPair.getPrivateKey(), keyPair.getPublicKey());
        }

    }

    @Override
    protected String doEncrypt(String text) {
        return this.rsa.encryptBase64(text, KeyType.PublicKey);
    }

    @Override
    protected String doDecrypt(String text) {
        return this.rsa.decryptStr(text, KeyType.PrivateKey);
    }
}
